<?php
/**
 * Contact Countries List Grid
 * This is the administration interface to add/update/delete 
 * contact countries.
 *
 * @author Xavier VILAIN
 * @package Hive\Ressource
 * @license #license-hive#
 *  
 */
use Fox\Behaviors;
use Fox\Html\Button;
use Hive\Address\Country;
use Fox\Html\Html;
use Fox\Generator;
use Fox\Dao\SqlFragment;
$xview = Xview::instance();
// Customizing
$customizing = Hive\Admin\Customizing::instance();
$customizing->trackSummaryPage(array('mod' =>'contacts','act'=>'countries','sac' => null));

if(!Fox\Authorization\Manager::check(Hive\Authorizations::CONTACT_COUNTRIES_W)) {
	echo $xview->accessDenied(Msg(Hive::BUNDLE,Hive::ERR_ADMIN_ACCES_DENIED),null,true);
	exit;
}
$language = Xview::instance()->language();
$reload = $xview->val('reload',false);
$screen = new Fox\Html\Screen('sStatuses');
$screen->pageTitle(Msg(Hive::BUNDLE,Hive::CONTACT_COUNTRIES_LIST));
$screen->message(Msg(Hive::BUNDLE,Hive::ADMIN_COUNTRIES_HELP_MESSAGE));

$query = Fox\Dao::infos(Country::className())
	->handle()->createQueryBuilder()
	->select('c.code','c.language','c.label as default_label','c.active','t.label')
	->from('address_countries','c')
	->leftJoin('c','address_country_i18n','t','t.code = c.code');

$fragment = new SqlFragment('t.language = ? OR c.language = ?',array($language,$language));
$data = $fragment->pushIn($query)->execute()->fetchAll(PDO::FETCH_ASSOC);

$grid = new Fox\Grid('countries');
$grid->source(Generator::url('contacts','countries'));
$grid->fieldcat(array(
				array('country_code','code'),
				'label',
				'active'));
$grid->fieldcat()->field('label')->setGenerator(Generator::useFunction(function($data) use($language){
	if($data['language'] == $language) {
		return $data['default_label'];
	}
	return $data['label'];
}));
$grid->layout()->scrollVertical(true);
$grid->setCoche(true);
$grid->initialize($data);
$grid->fieldcat()->behaviors(Behaviors::key(Generator::useElement('code')));
$grid->footer()->add(new Button('activate'))
	->color(Button::COLOR_GREEN)
	->behaviors(Behaviors::action(
		Generator::url('contacts','countries','modify',array('enable' => true)),
		false,
		null,
		null,
		false,
		'POST',
		'MC_countries',
		null,
		null,
		true,
		Generator::ajaxReload('MC_countries')
	));
$grid->footer()->add(new Button('deactivate'))
	->color(Button::COLOR_RED)
	->behaviors(Behaviors::action(
		Generator::url('contacts','countries','modify',array('enable' => false)),
		false,
		'MC_countries',
		null,
		false,
		'POST',
		'MC_countries',
		null,
		'MC_countries',
		true,
		Generator::ajaxReload('MC_countries')
	));
if($xview->isReloading()) {
	echo $grid->display();
} else {
	echo $screen->display();
	echo $grid->display();
}
